import 'dart:io';

import 'package:aihu_getx_app/app/interceptors/login_intercept_chain.dart';
import 'package:aihu_getx_app/app/modules/commons/model/client_base_config_model.dart';
import 'package:aihu_getx_app/app/modules/commons/model/login_res_model.dart';
import 'package:aihu_getx_app/app/routes/app_pages.dart';
import 'package:aihu_getx_app/utils/cache_keys.dart';
import 'package:aihu_getx_app/utils/constants.dart';
import 'package:aihu_getx_app/widgets/common_image.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:window_manager/window_manager.dart';

class Commons {
  static final isFullScreen = false.obs;
  static final isDeskApp =
      Platform.isMacOS || Platform.isWindows || Platform.isLinux;

  static String? getMqttClientId() {
    if (LoginInterceptChain.isLogin()) {
      LoginResModel? loginResModel = getLoginResModel();
      if (loginResModel != null) {
        return loginResModel.accessToken;
      }
    }
    return null;
  }

  static String? getMqttUsername() {
    if (LoginInterceptChain.isLogin()) {
      LoginResModel? loginResModel = getLoginResModel();
      if (loginResModel != null) {
        ClientBaseConfigModel config = getCurrentClientConfig();
        return "_sys_user_${config.tenantId}_${config.userType}_${loginResModel.userId}";
      }
    }
    return null;
  }

  static String? getWebsocketUrl() {
    if (LoginInterceptChain.isLogin()) {
      LoginResModel? loginResModel = getLoginResModel();
      if (loginResModel != null) {
        ClientBaseConfigModel config = getCurrentClientConfig();
        return "${config.serverApiUrl.replaceFirst("http", "ws")}/chat/service?app-id=${config.appId}&Authorization=Bearer ${loginResModel.accessToken}&tenant-id=${config.tenantId}";
      }
    }
    return null;
  }

  static LoginResModel? getLoginResModel() {
    ClientBaseConfigModel config = getCurrentClientConfig();
    late LoginResModel? lrm;
    if (config.idx.type == ClientType.d.type) {
      lrm = SpUtil.getObj(
        CacheKeys.adminLoginInfo,
        (v) => LoginResModel.fromJson(v as Map<String, dynamic>),
      );
    } else {
      lrm = SpUtil.getObj(
        CacheKeys.userLoginInfo,
        (v) => LoginResModel.fromJson(v as Map<String, dynamic>),
      );
    }
    return lrm;
  }

  static int getLastSplashPageIndex() {
    try {
      String? t = SpUtil.getString(CacheKeys.lastSplashPageIndex);
      if (TextUtil.isEmpty(t)) {
        return -1;
      }
      return Constants.clientBaseConfigData
          .indexWhere((element) => element.idx.type == t);
    } catch (e) {
      SpUtil.remove(CacheKeys.lastSplashPageIndex);
      return -1;
    }
  }

  static ClientBaseConfigModel getCurrentClientConfig({String? clientType}) {
    int idx = TextUtil.isEmpty(clientType)
        ? getLastSplashPageIndex()
        : Constants.clientBaseConfigData.indexWhere(
            (element) => element.idx.type == clientType,
          );
    if (idx < 0) {
      return Constants.clientBaseConfigData[0];
    }
    return Constants.clientBaseConfigData[idx];
  }

  static Future<bool>? setLastSplashPageIndex(int idx) {
    return SpUtil.putString(CacheKeys.lastSplashPageIndex,
        Constants.clientBaseConfigData[idx].idx.type);
  }

  static String getLastSplashPage() {
    int idx = getLastSplashPageIndex();
    if (idx < 0) {
      return Routes.splash;
    }
    return Constants.clientBaseConfigData[idx].indexPage;
  }

  static final List<Widget> actions = [
    IconButton(
      onPressed: () {
        Get.offAllNamed(Routes.splash);
      },
      icon: const Icon(Icons.swap_horiz_outlined),
    ),
  ];

  static AppBar appBar({
    String title = Constants.appName,
    String subTitle = "",
    List<Widget> actions = const [],
    Function()? refresh,
    alwaysShowRefresh = false,
    PreferredSizeWidget? bottom,
  }) {
    var isWindows = Platform.isWindows;
    var isMac = Platform.isMacOS;
    var isLinux = Platform.isLinux;
    var rawRoute = Get.rawRoute;
    return AppBar(
      leadingWidth: subTitle.isNotEmpty ? 160 : 60,
      leading: Row(
        children: [
          const SizedBox(
            width: 5,
          ),
          SizedBox(
            width: 40,
            height: 40,
            child: (rawRoute == null || rawRoute.isFirst)
                ? const CommonImage(
                    Constants.appBarLogoImage,
                    fit: BoxFit.cover,
                  )
                : IconButton(
                    onPressed: () {
                      Get.back();
                    },
                    icon: const Icon(Icons.arrow_back_ios),
                  ),
          ),
          Text(
            subTitle,
            style: const TextStyle(
              fontSize: 22,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
      title: Text(title,
          style: const TextStyle(
            fontSize: 22,
            fontWeight: FontWeight.bold,
          )),
      centerTitle: true,
      actions: (((alwaysShowRefresh || isWindows || isMac || isLinux) &&
                  refresh != null)
              ? <Widget>[
                  IconButton(
                    onPressed: () {
                      refresh();
                    },
                    icon: const Icon(Icons.refresh),
                  ),
                ]
              : <Widget>[]) +
          (isWindows
              ? <Widget>[
                  IconButton(
                    onPressed: () {
                      windowManager
                          .setFullScreen(!isFullScreen.value)
                          .then((value) {
                        return windowManager.isFullScreen();
                      }).then((value) {
                        isFullScreen.value = value;
                        return Future(() => value);
                      }).then((value) {
                        isFullScreen.value = value;
                        return Future(() => value);
                      }).then((value) => Get.forceAppUpdate());
                    },
                    icon: Obx(
                      () => Icon(isFullScreen.value
                          ? Icons.fullscreen_exit
                          : Icons.fullscreen),
                    ),
                  ),
                ]
              : <Widget>[]) +
          (actions.isEmpty ? Commons.actions : actions),
      bottom: bottom,
    );
  }
}
